package org.kie.jenkins.jobdsl.utils

import org.kie.jenkins.jobdsl.Utils

class EnvUtils {

    static String DEFAULT_ENVIRONMENT_NAME = 'default'

    static List<String> getAllEnvironments(def script) {
        String envsStr = Utils.getBindingValue(script, 'ENVIRONMENTS')
        PrintUtils.debug(script, "getAllEnvironments => from ${envsStr}")
        List<String> environments = envsStr.split(',').findAll { it != DEFAULT_ENVIRONMENT_NAME }
        PrintUtils.debug(script, "getAllEnvironments => to ${environments}")
        return environments
    }

    static boolean isEnvironmentEnabled(def script, String envName) {
        if (isDefaultEnvironment(script, envName)) {
            return true
        }
        def value = getEnvironmentValue(script, envName, 'ENABLED')
        PrintUtils.debug(script, "isEnvironmentEnabled ${envName} => ${value != '' ? value.toBoolean() : true}")
        return value != '' ? value.toBoolean() : true
    }

    static boolean isEnvironmentAutoGenerated(def script, String envName) {
        if (isDefaultEnvironment(script, envName)) {
            return true
        }
        def value = getEnvironmentValue(script, envName, 'AUTO_GENERATION')
        PrintUtils.debug(script, "isEnvironmentAutoGenerated ${envName} => ${value != '' ? value.toBoolean() : true}")
        return value != '' ? value.toBoolean() : true
    }

    static boolean isEnvironmentPullRequestDefaultCheck(def script, String envName) {
        if (isDefaultEnvironment(script, envName)) {
            return true
        }
        def value = getEnvironmentValue(script, envName, 'PULL_REQUEST_DEFAULT_CHECK')
        PrintUtils.debug(script, "isEnvironmentPullRequestDefaultCheck ${envName} => ${value != '' ? value.toBoolean() : true}")
        return value != '' ? value.toBoolean() : false
    }

    static boolean isDefaultEnvironment(def script, String envName) {
        return envName == ''
    }

    static boolean isEnvironmentDefined(def script, String envName) {
        if (isDefaultEnvironment(script, envName)) {
            return true
        }
        boolean value = Utils.hasBindingValuesStartingWith(script, createEnvironmentsKeyPrefix(script, envName))
        PrintUtils.debug(script, "isEnvironmentDefined ${envName} => ${value}")
        return value
    }

    static List<String> getAllEnabledEnvironments(def script) {
        List<String> enabledEnvironments = getAllEnvironments(script).findAll { isEnvironmentEnabled(script, it) }
        PrintUtils.debug(script, "getAllEnabledEnvironments => ${enabledEnvironments}")
        return enabledEnvironments
    }

    static List<String> getAllEnabledEnvironmentsForIds(def script, List<String> includeEnvironmentIds, List<String> excludeEnvironmentIds) {
        List<String> filteredEnvironments = getAllEnabledEnvironments(script).findAll { hasEnvironmentIds(script, it, includeEnvironmentIds) &&
                !hasEnvironmentIds(script, it, excludeEnvironmentIds) }
        PrintUtils.debug(script, "getAllEnabledEnvironmentsForIds, include='${includeEnvironmentIds}', exclude='${excludeEnvironmentIds}' => ${filteredEnvironments}")
        return filteredEnvironments
    }

    static List<String> getAllAutoGeneratedEnvironments(def script) {
        List<String> environments = getAllEnabledEnvironments(script).findAll { isEnvironmentAutoGenerated(script, it) }
        PrintUtils.debug(script, "getAllAutoGeneratedEnvironments => ${environments}")
        return environments
    }

    static List<String> getAllAutoGeneratedEnvironmentsForIds(def script, List<String> includeEnvironmentIds, List<String> excludeEnvironmentIds) {
        List<String> environments = getAllEnabledEnvironmentsForIds(script, includeEnvironmentIds, excludeEnvironmentIds).findAll { isEnvironmentAutoGenerated(script, it) }
        PrintUtils.debug(script, "getAllAutoGeneratedEnvironmentsForIds => ${environments}")
        return environments
    }

    static Map getEnvironmentEnvVars(def script, String envName) {
        String keyPrefix = "${createEnvironmentsKeyPrefix(script, envName)}ENV_VARS_"
        PrintUtils.debug(script, "Looking for env vars for env ${envName}. Key prefix is ${keyPrefix}")
        Map envVars = Utils.getBindingValuesStartingWith(script, keyPrefix)
                                .collectEntries {
                                    ["${it.replace(keyPrefix, '')}", Utils.getBindingValue(script, it)]
                                }
        PrintUtils.debug(script, "Got env vars = ${envVars}")
        return envVars
    }

    static String getEnvironmentEnvVar(def script, String envName, String envKey) {
        // Using find method as the keys are stored as gstring
        // and it creates problem when searching for a gstring/string key with `map.get(key)` ...
        return getEnvironmentEnvVars(script, envName).find { it.key == envKey }?.value
    }

    static List<String> getEnvironmentIds(def script, String envName) {
        return Utils.getBindingValue(script, "${createEnvironmentsKeyPrefix(script, envName)}IDS").split(',')
    }

    static boolean hasEnvironmentId(def script, String envName, String id) {
        return getEnvironmentIds(script, envName).contains(id)
    }

    static boolean hasEnvironmentIds(def script, String envName, List<String> ids) {
        return ids.every { hasEnvironmentId(script, envName, it) }
    }

    private static def getEnvironmentValue(def script, String envName, String envKey) {
        String key = "${createEnvironmentsKeyPrefix(script, envName)}${envKey}"
        def value = Utils.getBindingValue(script, key)
        PrintUtils.debug(script, "getEnvironmentValue for env ${envName}: ${key} = ${value}")
        return value
    }

    private static String createEnvironmentsKeyPrefix(def script, String envName) {
        String envId = isDefaultEnvironment(script, envName) ? DEFAULT_ENVIRONMENT_NAME : envName
        return "ENVIRONMENTS_${envId.toUpperCase()}_"
    }
}
